package com.banmao.CarlCamp.Day04;

/**
 * https://leetcode.cn/problems/remove-nth-node-from-end-of-list/
 */
public class LC19 {

    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode[] arr = new ListNode[32];
        int size = 0;
        ListNode dummyHead = new ListNode(-1);
        dummyHead.next = head;

        // 直接将虚拟头节点也一起放入数组中
        arr[size++] = dummyHead;
        ListNode cur = dummyHead;
        while (cur != null) {
            // 通过遍历，将链表的节点放入数组
            arr[size++] = cur;
            cur = cur.next;
        }
        // 要删除的节点下标就是 size - n，因为 size 实际上是 总长度 + 1
        int delIndex = size - n;
        // 剩下的就是删除操作了
        ListNode preNode = arr[delIndex - 1];
        ListNode delNode = arr[delIndex];
        preNode.next = delNode.next;
        return dummyHead.next;
    }

    public class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }
}
